package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
@Topic(TopicConfig.VMS_RESULT_TOPIC)//
public class ListenVmResultHandler implements MsgHandler {
    @Autowired
    VendoutRunningService vendoutRunningService;
    @Autowired
    ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //1.Json转换对应的协议类
        VendoutResultContract contract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        //2.参数校验
        if (contract == null) {
            log.info("接收售货机终端协议类，传递的参数不能为空");
            throw new LogicException("接收售货机终端协议类，传递的参数不能为空");
        }
        //获取参数中的相关商品信息
        VendoutData vendoutData = contract.getVendoutData(); //订单号 商品id innercode 货道号
        //3.根据innercode获取售货机货道的信息
        List<ChannelEntity> ChannelList = channelService.getChannelesByInnerCode(contract.getInnerCode());

        //4判断状态 //出货成功
        if (!contract.isSuccess()) {
            //5.2根据商品id和货道编码  获取对应商品的货道信息
            ChannelList.forEach(channelEntity -> {
                if (channelEntity.getSkuId() == vendoutData.getSkuId() && channelEntity.getChannelCode().equals(vendoutData.getChannelCode())) {
                    //对商品库存进行减一操作
                    channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity() + 1);
                    channelService.updateById(channelEntity);
                }
            });
            log.info("机器出货失败，补偿");
        } else {
            //根据订单号查询对应流水记录
            VendoutRunningEntity vendoutRunning = vendoutRunningService.getOne(Wrappers.<VendoutRunningEntity>lambdaQuery()
                    .eq(VendoutRunningEntity::getOrderNo, vendoutData.getOrderNo()));
            //出货成功 货存补偿
            //修改流水表
            vendoutRunning.setStatus(true);
            //更新流水的状态
            vendoutRunningService.updateById(vendoutRunning);

            log.info("机器出货成功");
        }
    }
}
